#include <algorithm>
#include "TaskManager.h"

int TaskManager::Execute()
{
	while (m_taskList.size())
	{
		for (TaskList_t::iterator it = m_taskList.begin(); it != m_taskList.end();++it)
		{
			ITask* t = (ITask*)(*it);
			if (!t->m_canKill)
				t->Update();
		}
		for (TaskList_t::iterator it = m_taskList.begin(); it != m_taskList.end();)
		{
			Pointer<ITask> t = (*it);
			 ++it;
			if (t->m_canKill)
			{
				t->Stop();
				m_taskList.remove(t);
				t = 0;
			}
		}
	}
	return 0;
};

bool TaskManager::AddTask( Pointer<ITask>& task )
{
	if (!task->Start())
		return false;
	TaskList_t::iterator it;
	for (it = m_taskList.begin(); it != m_taskList.end(); ++it)
	{
		Pointer<ITask> &comp = (*it);
		if (comp->m_priority > task->m_priority)
			break;
	}
	m_taskList.insert(it, task);
	return true;
};

void TaskManager::SuspendTask( Pointer<ITask> &task )
{
	TaskList_t::iterator it;
	if ((it = std::find(m_taskList.begin(), m_taskList.end(), task)) != m_taskList.end())
	{
		task->OnSuspend();
		m_pausedTaskList.push_back(task);
		m_taskList.remove(task);
	}
};

void TaskManager::RemoveTask( Pointer<ITask>& task )
{
	if (std::find(m_taskList.begin(), m_taskList.end(), task) != m_taskList.end())
	{
		task->m_canKill = true;
	}
};

void TaskManager::KillAllTasks()
{
	for (TaskList_t::iterator it = m_taskList.begin(); it != m_taskList.end(); ++it)
	{
		(*it)->m_canKill = true;
	}
};

void TaskManager::ResumeTask( Pointer<ITask>& task )
{
	TaskList_t::iterator it;
	if ((it = std::find(m_pausedTaskList.begin(), m_pausedTaskList.end(), task)) != m_pausedTaskList.end())
	{
		task->OnResume();
		m_taskList.push_back(task);
		m_pausedTaskList.remove(task);
	}
}